var _ = require('lodash');
var config = require('../../config/environment');
var moment = require('moment');
var request = require('request');
var URI = require('urijs');
var Promise = require("bluebird");
Promise.promisifyAll(require("request"));
var redis = require("redis");
var async = require('async');
var db = require('../../sqldb/index');


var kue = require('kue'),
    queue = kue.createQueue(config.kue);

queue.setMaxListeners(1000);


queue.on('job complete', function (id, result) {
    kue.Job.get(id, function (err, job) {
        if (err) return;
    });
}).on('job failed', function (id, result) {
    kue.Job.get(id, function (err, job) {
        if (err) return;
    });
});

/**
 * 执行任务
 */
queue.process('execRule', config.kueWorkers, function (job, done) {
   done();
});

process.once('SIGTERM', function (sig) {
    queue.shutdown(5000, function (err) {
        console.log('Kue shutdown: ', err || '');
        process.exit(0);
    });
});

// 重启所有未完成的通知
queue.active(function (err, ids) {
    ids.forEach(function (id) {
        kue.Job.get(id, function (err, job) {
            // Your application should check if job is a stuck one
            console.log('---------重启job----------');
            console.log(job.data);
            job.inactive();
        });
    });
});

kue.app.listen(3000);
exports.queue = queue;
exports.kue = kue;